<?php


namespace app\task\cron\coupon;

use api\channel\coupon\YiQiDaHandler;
use app\model\BaseSupplier;
use app\model\CouponProductChannel;
use Carbon\Carbon;
use yunwuxin\cron\Task;
use app\model\CouponOrder;

/**
 * 亿奇达
 *
 * 同步价格：4分钟执行1次，后期根据实际运行情况做调整
 */
class ModifyYiQiDaPrice extends Task
{
    /**
     * 配置指令.
     */
    protected function configure()
    {
        // 分 时 日 月 周
        $this->expression = '*/4 * * * *';
    }


    protected function handle()
    {
        echo 'CPS亿奇达调价-开始' . PHP_EOL;
        $lockKey = 'coupon_place.quanyi.modify_price_lock';
        $lockVal = cache($lockKey);
        //生产环境才执行，其他环境暂时不执行
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;
            return true;
        }
        cache($lockKey, 1, 60);
        //优化---数据分批处理
        CouponProductChannel::query()->where('type', CouponProductChannel::TYPE_YQD)
            ->where('sku_type', CouponProductChannel::SKU_TYPE_ZC)
            ->where('advance_price', '>', 0)
            ->where('advance_time', '<=', time())
            ->where('advance_time', '>', 0)
            ->chunk(30, function ($list){
                if (empty($list)) {
                    return false;
                }
                /**
                 * @var CouponProductChannel $couponProductChannel
                 */
                foreach ($list as $couponProductChannel) {
                    if ($couponProductChannel->advance_time > time()) {
                        continue;
                    }
                    //已经修改过的不在修改
                    if ($couponProductChannel->advance_price == 0){
                        continue;
                    }
                    if ($couponProductChannel->cost_price == $couponProductChannel->advance_price) {
                        continue;
                    }
                    $couponProductChannel->cost_price = $couponProductChannel->advance_price;
                    $couponProductChannel->advance_price = 0;
                    $couponProductChannel->advance_time = 0;
                    $couponProductChannel->save();
                }
            });

        cache($lockKey, null);
        echo 'CPS亿奇达调价-结束'.PHP_EOL;
    }
}